/**
 * @description 桥梁服务
 */

import { isPlus, keys, setUserKeys, storeStorage, StorePipe, StoreClass, piper } from './service.js'
import { strer, parser, base64, loger } from '@daelui/dogjs/dist/components'
import uniFiler from '@/components/libs/uni-filer.js'

// 桥梁相关
const storeBridge = new StorePipe()
storeBridge.setKey(keys.bridge)
// 桥梁病害存储器
const storeBD = new StorePipe()
storeBD.setKey(keys.bd)

export {
  keys, setUserKeys, storeStorage, piper,
  StoreClass,
  storeBridge, storeBD
}

// 同步桥梁信息
export const syncBridgeInfo = function (view) {
  let $u = view.$u
  view = { $u: view.$u, vuex_config: view.vuex_config }
  return new Promise((resolve, reject) => {
    // 查看网络状态
    uni.getNetworkType({
      success: (res) => {
        if (res.networkType !== 'none') {
          uni.showLoading({
            title: '加载中'
          })
          let defers = [
            // 病害信息
            $u.api.bridge.queryBaseData({}, { cache: false }).then(res => {
              let data = res?.data || {}
              // 更新公用病害相关信息
              storeBridge.setItem(keys.bridgeDiseaseTagsList, data.judgeDiseaseTagsList || [])
              storeBridge.setItem(keys.bridgeDiseaseTypeList, data.judgeDiseaseTypeList || [])
              storeBridge.setItem(keys.bridgeDiseaseTypeScaleList, data.judgeDiseaseTypeScaleList || [])
              storeBridge.setItem(keys.bridgeSimpleTargetList, data.judgeSimpleTargetList || [])
              storeBridge.setItem(keys.bridgeStructTypeList, data.judgeStructTypeList || [])
            }).catch(e => loger.error(e)),
            $u.api.bridge.queryConfig({}, { cache: false }).then(async res => {
              let data = res?.data || {}
              let bridgeList = data.bridgeInfoList || []
              // 更新用户桥梁相关信息
              queryBridges().then(list => {
                list = Array.isArray(list) ? list : []
                // 无任何桥梁
                if (!list.length) {
                  return Promise.resolve(saveBridges(bridgeList)).then(() => {
                    // 桥梁图片处理
                    return syncImages(bridgeList, view)
                  })
                }
                // 新增的桥梁
                let inserts = bridgeList.filter(item => {
                  let node = list.find(node => String(node.bridgeId) === String(item.bridgeId))
                  return !node
                })
                if (inserts && inserts.length) {
                  return syncImages(inserts, view, { isUpdateStore: false }).finally(() => {
                    list = list.concat(inserts)
                    return saveBridges(list)
                  })
                }
              })
              // 项目计划信息
              storeBridge.setItem(keys.bridgeProjectList, data.periodicProjectList || [])
              storeBridge.setItem(keys.bridgeInspectionList, data.periodicInspectionList || [])
              storeBridge.setItem(keys.bridgeComponentList, data.judgeComponentList || [])
              // 病害列表
              let diseaseList = await piper.dber.table('bridge_disease').select()
              if (!diseaseList || !diseaseList.length) {
                // 添加病害
                insertDiseaseAll(data.periodicInspectionDiseaseList || []).then(() => {
                  // 添加病害图片
                  let imageList = data.periodicDiseaseImagesList || []
                  insertDiseaseImage(imageList).then(() => {
                    // 病害图片下载处理
                    downloadDiseaseImages(imageList, view)
                  }).catch(e => loger.error(e))
                }).catch(e => loger.error(e))
              }
              // 现场信息
              let bridgeSiteInfoList = data.bridgeSiteInfoList || []
              // 查看现场信息
              queryLocaleInfos().then(list => {
                if (!list || !list.length) {
                  Promise.resolve(saveLocaleInfos(bridgeSiteInfoList)).then(() => {
                    // 现场图片处理
                    syncInfoImages(bridgeSiteInfoList, view)
                  })
                }
              })
              storeBridge.setItem(keys.bridgeSiteInfoList, bridgeSiteInfoList)
            }).catch(e => loger.error(e)),
            // 字段与公共信息
            $u.api.system.queryDictList({}).then(async res => {
              let data = res?.data || {}
              storeBridge.setItem(keys.dict, data)
            }).catch(e => loger.error(e)),
            // 部门-查询树
            $u.api.system.queryDeptTree().then(async res => {
              let data = res?.data || []
              storeBridge.setItem(keys.dept, data || [])
            }).catch(e => loger.error(e)),
            // 路线-查询列表
            $u.api.system.queryRouteList().then(async res => {
              let data = res?.data || []
              storeBridge.setItem(keys.route, data || [])
            }).catch(e => loger.error(e))
          ]
          Promise.allSettled(defers).finally(() => {
            uni.hideLoading()
            resolve()
          })
        } else {
          resolve()
        }
      },
      fail: () => {
        resolve()
      }
    })
  })
}

// 绑定计划后同步项目、计划、桥梁信息
export const syncBindPlanAbout = function (view) {
  let $u = view.$u
  view = { $u: view.$u, vuex_config: view.vuex_config }

  let defers = [
    $u.api.bridge.queryConfig({
      bridgeInfoList: {},
      periodicProjectList: {},
      periodicInspectionList: {}
    }, { cache: false }).then(async res => {
      let data = res?.data || {}
      let bridgeList = data.bridgeInfoList || []
      // 更新用户桥梁相关信息
      return Promise.allSettled([
        queryBridges().then(list => {
          list = Array.isArray(list) ? list : []
          // 无任何桥梁
          if (!list.length) {
            return Promise.resolve(saveBridges(bridgeList)).then(() => {
              // 桥梁图片处理
              return syncImages(bridgeList, view)
            })
          }
          // 新增的桥梁
          let inserts = bridgeList.filter(item => {
            let node = list.find(node => String(node.bridgeId) === String(item.bridgeId))
            return !node
          })
          if (inserts && inserts.length) {
            return syncImages(inserts, view, { isUpdateStore: false }).finally(() => {
              list = list.concat(inserts)
              return saveBridges(list)
            })
          }
        }),
        // 项目计划信息
        storeBridge.setItem(keys.bridgeProjectList, data.periodicProjectList || []),
        storeBridge.setItem(keys.bridgeInspectionList, data.periodicInspectionList || [])
      ])
    }).catch(e => loger.error(e))
  ]

  return Promise.allSettled(defers)
}

// 查询用户关联的病害相关信息
export const queryReleated = function (params, { view } = {}) {
  return view.$u.api.bridge.queryConfig(
    params,
    { cache: false }
  )
}

// 查询桥梁列表
export const queryBridgeList = function () {
  return storeBridge.getItem(keys.bridgeList)
}

// 保存桥梁列表
export const saveBridgeList = function (list) {
  list = Array.isArray(list) ? list : []
  return storeBridge.setItem(keys.bridgeList, list)
}

// 查询桥梁结构类型列表
export const queryStructTypeList = function () {
  return storeBridge.getItem(keys.bridgeStructTypeList)
}

// 查询桥梁检查项目列表
export const queryProjectList = function (parmas) {
  return Promise.resolve(storeBridge.getItem(keys.bridgeProjectList)).then(list => {
    list = Array.isArray(list) ? list : []
    return list
  })
}

// 查询桥梁计划列表
export const queryInspectionList = function (params) {
  params = params || {}
  return Promise.resolve(storeBridge.getItem(keys.bridgeInspectionList)).then(list => {
    list = Array.isArray(list) ? list : []
    if (params.inspectionId) {
      list = list.filter(item => String(item.inspectionId) === String(params.inspectionId))
    }
    return list
  })
}

// 查询桥梁病害列表
export const queryDiseaseList = function (params) {
  params = params || {}
  let condition = {}
  if (params.bridgeId) {
    condition.bridgeId = params.bridgeId
  }
  if (params.inspectionId) {
    condition.inspectionId = params.inspectionId
  }
  if (params.id) {
    condition.id = params.id
  }
  return Promise.resolve(piper.dber.table('bridge_disease').select(condition)).then(list => {
    list = Array.isArray(list) ? list : []
    list.forEach(item => {
      if (item.cache && !/\{|\[/m.test(item.cache)) {
        item.cache = base64.decode(item.cache)
      }
    })
    if (params.inspectionId) {
      list = list.filter(item => String(item.inspectionId) === String(params.inspectionId))
    }
    if (params.structTypeId) {
      list = list.filter(item => String(item.structTypeId) === String(params.structTypeId))
    }
    list.forEach(item => {
      item.cache = parser.parse(item.cache)
    })
    return list
  })
}

// 添加病害
export const insertDisease = function (...args) {
  let node = args[0]
  node = { ...node }
  node.cache = parser.stringify(node.cache)
  if (node.cache && /\{|\[/m.test(node.cache)) {
    node.cache = base64.encode(node.cache)
  }
  return piper.dber.table('bridge_disease').insert(node)
}

// 添加病害
export const insertDiseaseAll = function (...args) {
  let node = args[0]
  let nodes = Array.isArray(node) ? node : [node]
  nodes.forEach(node => {
    node = { ...node }
    node.cache = parser.stringify(node.cache)
    if (node.cache && /\{|\[/m.test(node.cache)) {
      node.cache = base64.encode(node.cache)
    }
  })
  return piper.dber.table('bridge_disease').insertAll(nodes)
}

// 更新病害
export const updateDisease = function (params) {
  let node = params
  node = { ...node }
  node.cache = parser.stringify(node.cache)
  if (node.cache && /\{|\[/m.test(node.cache)) {
    node.cache = base64.encode(node.cache)
  }
  return piper.dber.table('bridge_disease').update(node, { id: params.id })
}

// 更新病害
export const updateDiseaseAll = function (params) {
  let node = params
  let nodes = Array.isArray(node) ? node : [node]
  nodes.forEach(node => {
    node = { ...node }
    node.cache = parser.stringify(node.cache)
    if (node.cache && /\{|\[/m.test(node.cache)) {
      node.cache = base64.encode(node.cache)
    }
  })
  return piper.dber.table('bridge_disease').updateAll(nodes)
}

// 删除病害
export const deleteDisease = function (params, deleteImages) {
  return piper.dber.table('bridge_disease').delete(params).then(() => {
    // 删除病害图片
    if (deleteImages) {
      return piper.dber.table('bridge_disease_image').delete(
        { id: String(deleteImages) },
        { operators: [{field: 'id', operator: 'IN'}] },
      )
    }
  })
}

// 查询桥梁病害类型
export const queryDiseaseTypeList = function (params) {
  params = params || {}
  return Promise.resolve(storeBridge.getItem(keys.bridgeDiseaseTypeList)).then(list => {
    list = Array.isArray(list) ? list : []
    if (params.code) {
      list = list.filter(item => String(item.code) === String(params.code))
    }
    return list
  })
}

// 查询桥梁病害位置
export const queryDiseaseTagList = function (params) {
  params = params || {}
  return Promise.resolve(storeBridge.getItem(keys.bridgeDiseaseTagsList)).then(list => {
    list = Array.isArray(list) ? list : []
    if (params.partsId) {
      list = list.filter(item => String(item.partsId) === String(params.partsId))
    }
    if (params.structTypeId) {
      list = list.filter(item => String(item.structTypeId) === String(params.structTypeId))
    }
    return list
  })
}

// 查询桥梁病害标度
export const queryDiseaseTypeScaleList = function (params) {
  params = params || {}
  return Promise.resolve(storeBridge.getItem(keys.bridgeDiseaseTypeScaleList)).then(list => {
    list = Array.isArray(list) ? list : []
    if (params.code) {
      list = list.filter(item => String(item.code) === String(params.code))
    }
    return list
  })
}

// 查询桥梁部件列表
export const queryPartList = function (params) {
  params = params || {}
  return Promise.resolve(storeBridge.getItem(keys.bridgeList)).then(list => {
    list = Array.isArray(list) ? list : []
    let bridge = list.find(item => String(item.bridgeId) === String(params.bridgeId)) || {}
    let judgeStructTypeList = bridge.judgeStructTypeList
    judgeStructTypeList = Array.isArray(judgeStructTypeList) ? judgeStructTypeList : []
    let struct = judgeStructTypeList.find(item => String(item.typeId) === String(params.structTypeId)) || {}
    let partsList = struct.partsList
    partsList = Array.isArray(partsList) ? partsList : []
    return partsList
  })
}

// 查询桥梁构件列表
export const queryComponentList = function (params) {
  params = params || {}
  return Promise.resolve(storeBridge.getItem(keys.bridgeComponentList)).then(list => {
    list = Array.isArray(list) ? list : []
    if (params.bridgeId) {
      list = list.filter(item => String(item.bridgeId) === String(params.bridgeId))
    }
    if (params.partsId) {
      list = list.filter(item => String(item.partsId) === String(params.partsId))
    }
    return list
  })
}

// 查询桥梁图片
export const queryImages = function ({images, imageIds, view} = {}) {
  images = images || ''
  images = String(images).split(',')
  images = images.filter(item => !!item)
  imageIds = imageIds || ''
  imageIds = String(imageIds).split(',')
  imageIds = imageIds.filter(item => !!item)
  if (!images.length) {
    return Promise.resolve([])
  }
  let data = images.map((item, i) => {
    return {
      id: imageIds[i] || strer.urid(12, false, true),
      path: item,
      url: view.vuex_config.adminPath + item,
      name: item.replace(/^.+\//, ''),
      localUrl: ''
    }
  })
  let defers = []
  data.forEach(item => {
    let defer = new Promise((resolve, reject) => {
      uni.request({
        url: item.url,
        method: 'GET',
        responseType: 'arraybuffer',
        success: (res) => {
          try {
            if (res.statusCode === 200) {
              let base64 = uni.arrayBufferToBase64(res.data)
              base64 = 'data:image/jpeg;base64,' + base64
              uniFiler.base64ToPath(base64).then((path) => {
                item.localUrl = path
                resolve()
              }).catch((e) => {
                resolve(e)
              })
            } else {
              reject(e)
            }
          } catch (e) {
            reject(e)
          }
        },
        error (e) {
          reject(e)
        }
      })
    })

    defers.push(defer)
  })
  return Promise.allSettled(defers).then(function(){
    return data
  })
}

// 同步桥梁图片
export const syncImages = function (bridges, view, { isUpdateStore } = {}) {
  bridges = Array.isArray(bridges) ? bridges : []
  let defers = []
  bridges.forEach(node => {
    if (!node || (!node?.mediaInfo?.facadeImages && !node?.mediaInfo?.frontImages && !node?.mediaInfo?.typicalImages)) {
      return true
    }
    [
      { images: node?.mediaInfo?.facadeImages, imageIds: node?.mediaInfo?.facadeImageIds, key: 'facadeImages' },
      { images: node?.mediaInfo?.frontImages, imageIds: node?.mediaInfo?.frontImageIds, key: 'frontImages' },
      { images: node?.mediaInfo?.typicalImages, imageIds: node?.mediaInfo?.typicalImageIds, key: 'typicalImages' }
    ].forEach(item => {
      defers.push(
        queryImages({
          view,
          images: item.images,
          imageIds: item.imageIds
        }).then(list => {
          node.cache = node.cache || {}
          node.cache[item.key] = list
        })
      )
    })
  })
  return Promise.allSettled(defers).then(function(){
    if (isUpdateStore !== false) {
      return Promise.resolve(storeBridge.setItem(keys.bridgeList, bridges)).then(() => {
        return bridges
      })
    }
    return bridges
  })
}

// 查询桥梁数据
export const queryBridges = function () {
  return Promise.resolve(storeBridge.getItem(keys.bridgeList))
}

// 保存桥梁数据
export const saveBridges = function (bridges) {
  return Promise.resolve(storeBridge.setItem(keys.bridgeList, bridges))
}

// 查询桥梁病害图片
export const queryDiseaseImages = function ({id, view} = {}) {
  let images = id || ''
  images = String(images)
  if (!images.length) {
    return Promise.resolve([])
  }
  return Promise.resolve(piper.dber.table('bridge_disease_image').select(
    { id: String(images) },
    { operators: [{field: 'id', operator: 'IN'}] },
  )).then(data => {
    data = Array.isArray(data) ? data : []
    data = data.map(item => {
      return {
        id: item.id,
        name: item.name,
        localUrl: item.localUrl,
        paths: view.vuex_config.adminPath + item.path,
        path: item.path,
        inspectionId: item.inspectionId,
        isInsert: item.isInsert,
        isDelete: item.isDelete,
        url: ''
      }
    })
    let defers = []
    data.forEach(item => {
      if (item.localUrl) {
        return true
      }
      defers.push(item)
    })
    defers = downloadDiseaseImages(defers, view)
    return Promise.allSettled([defers]).then(function(){
      return data
    })
  })
}

// 查询桥梁病害图片
export const queryDiseaseImageList = function (params) {
  return Promise.resolve(piper.dber.table('bridge_disease_image').select(params))
}

// 添加桥梁病害图片
export const insertDiseaseImage = function (data, options) {
  return Promise.resolve(piper.dber.table('bridge_disease_image').insert(data, options))
}

// 更新桥梁病害图片
export const updateDiseaseImage = function (data, condition) {
  return Promise.resolve(piper.dber.table('bridge_disease_image').update(data, condition))
}

// 删除桥梁病害图片
export const deleteDiseaseImage = function (data, options) {  // 删除本地图片文件
  options = options || {}
  // 删除本地图片文件
  return queryDiseaseImageList(data, { operators: [{field: 'id', operator: 'IN'}] }).then(list => {
    list = Array.isArray(list) ? list : []
    list = list.filter(item => !!item.localUrl)
    let defer = Promise.resolve()
    // 删除本地存储的图片文件
    if (isPlus && options.isDeleteLocal !== false) {
      list.forEach(item => {
        defer = defer.then(() => {
          return deleteLocalImage(item)
        })
      })
    }
    return Promise.resolve(piper.dber.table('bridge_disease_image').delete(data, options))
  })
}

// 删除本地图片
export const deleteLocalImage = function (item) {
  item = item || {}
  if (!/doc/i.test(item.localUrl) || !isPlus) {
    return Promise.resolve(true)
  }
  return new Promise((resolve, reject) => {
    plus.io.resolveLocalFileSystemURL(item.localUrl, function(entry) {
      entry.remove(function(e) {
        resolve(e)
      }, function(e) {
        loger.error(e)
        reject(e)
      })
    })
  })
}

// 同步桥梁病害图片
export const syncDiseaseImages = function (diseases, view) {
  diseases = Array.isArray(diseases) ? diseases : []
  let defers = []
  diseases.forEach(node => {
    if (!node || !node.images) {
      return true
    }
    defers.push(
      queryDiseaseImages({
        view,
        id: node.images
      }).then(list => {
        node.cache = parser.parse(node.cache || {})
        node.cache.images = list
        node.cache = parser.stringify(node.cache)
      })
    )
  })
  return Promise.allSettled(defers).then(function(){
    updateDiseaseAll(diseases)
    return diseases
  })
}

// 加载病害图片
export const downloadDiseaseImages = function (list, view) {
  list = Array.isArray(list) ? list : []
  let defers = []
  list.forEach(item => {
    let defer = new Promise((resolve, reject) => {
      uni.request({
        url: view.vuex_config.adminPath + item.path,
        method: 'GET',
        responseType: 'arraybuffer',
        success: (res) => {
          try {
            if (res.statusCode === 200) {
              let base64 = uni.arrayBufferToBase64(res.data)
              base64 = 'data:image/jpeg;base64,' + base64
              uniFiler.base64ToPath(base64).then((path) => {
                item.localUrl = path
                resolve()
              }).catch((e) => {
                loger.error(e)
                resolve(e)
              })
            } else {
              reject(res)
            }
          } catch (e) {
            loger.error(e)
            reject(e)
          }
        },
        error (e) {
          reject(e)
        }
      })
    })
  
    defers.push(defer)
  })

  return Promise.allSettled(defers).then(() => {
    let data = list.filter(item => {
      return item.localUrl
    }).map(item => {
      return {
        id: item.id,
        localUrl: item.localUrl
      }
    })
    return piper.dber.table('bridge_disease_image').updateAll(data)
  }).then(function(){
    loger.log('桥梁病害图片加载完成')
    return list
  })
}

// 查询现场信息数据
export const queryLocaleInfos = function () {
  return Promise.resolve(storeBridge.getItem(keys.bridgeSiteInfoList))
}

// 保存现场信息数据
export const saveLocaleInfos = function (list) {
  return Promise.resolve(storeBridge.setItem(keys.bridgeSiteInfoList, list))
}

// 同步现场图片
export const syncInfoImages = function (infos, view, { isUpdateStore } = {}) {
  infos = Array.isArray(infos) ? infos : []
  let defers = []
  infos.forEach(node => {
    if (!node || !node?.images) {
      return true
    }
    [
      { images: node?.images, imageIds: node?.imageIds, key: 'localeImages' }
    ].forEach(item => {
      defers.push(
        queryImages({
          view,
          images: item.images,
          imageIds: item.imageIds
        }).then(list => {
          node.cache = node.cache || {}
          node.cache[item.key] = list
        })
      )
    })
  })
  return Promise.allSettled(defers).then(function(){
    if (isUpdateStore !== false) {
      return Promise.resolve(storeBridge.setItem(keys.bridgeSiteInfoList, infos)).then(function(){
        return infos
      })  
    }
    return infos
  })
}

// 按键查询字典
export const queryDictListByKey = function ({ key } = {}) {
  return Promise.resolve(storeBridge.getItem(keys.dict)).then(map => {
    map = map || {}
    let list = map[key]
    list = Array.isArray(list) ? list : []
    return {
      data: list
    }
  })
}

// 部门-查询树
export const queryDeptTree = function ({ key } = {}) {
  return Promise.resolve(storeBridge.getItem(keys.dept)).then(list => {
    list = Array.isArray(list) ? list : []
    return {
      data: list
    }
  })
}

// 路线-查询列表
export const queryRouteList = function ({ key } = {}) {
  return Promise.resolve(storeBridge.getItem(keys.route)).then(list => {
    list = Array.isArray(list) ? list : []
    return {
      data: list
    }
  })
}
